<?php
class WeatherMapDataSource_rrd extends WeatherMapDataSource {
	function Init(&$map) {
		error_log('WeatherMapDataSource_rrd - Init');
		return true;
	}

	function Recognise($targetstring) {
		error_log('WeatherMapDataSource_rrd - Recognise');
		if(preg_match("/^(.*\.rrd):([\-a-zA-Z0-9_]+):([\-a-zA-Z0-9_]+)$/",$targetstring,$matches)) {
			return TRUE;
		} elseif(preg_match("/^(.*\.rrd)$/",$targetstring,$matches)) {
			return TRUE;
		} else return FALSE;
	}

		
	function wmrrd_read_from_php_rrd($rrdfile,$cf,$start,$end,$dsnames, &$data ,&$map, &$data_time,&$item)
	{
			// for the php-rrdtool module, we use an array instead...
			$rrdparams = array("AVERAGE","--start",$start,"--end",$end);
			$rrdreturn = rrd_fetch ($rrdfile,$rrdparams,count($rrdparams));
			//echo '<pre>'.print_r($rrdreturn,1).'</pre>';
			// XXX - figure out what to do with the results here
			$now = $rrdreturn['start'];
			$n=0;
			$data[IN] = $rrdreturn['data'][0];
			$data[OUT] = $rrdreturn['data'][1];			
			/*
			do {
				$now += $rrdreturn['step'];
				//print "$now - ";
				for($i=0;$i<$rrdreturn['ds_cnt'];$i++)
				{
					//print $rrdreturn['ds_namv'][$i] . ' = '.$rrdreturn['data'][$n++]." ";
				}
				//print "\n";
			} while($now <= $rrdreturn['end']);*/
			//print_r($rrdreturn);
	}
	

	// Actually read data from a data source, and return it
	// returns a 3-part array (invalue, outvalue and datavalid time_t)
	// invalue and outvalue should be -1,-1 if there is no valid data
	// data_time is intended to allow more informed graphing in the future
	function ReadData($targetstring, &$map, &$item) {
		global $config;
		error_log('WeatherMapDataSource_rrd - Read');
		error_log('Reading External Data');
		$dsnames[IN] = "traffic_in";
		$dsnames[OUT] = "traffic_out";
		$data[IN] = NULL;
		$data[OUT] = NULL;
		$SQL[IN] = 'select null';
		$SQL[OUT] = 'select null';
		$rrdfile = $targetstring;
		if($map->get_hint("rrd_default_in_ds") != '') {
			$dsnames[IN] = $map->get_hint("rrd_default_in_ds");
			debug("Default 'in' DS name changed to ".$dsnames[IN].".\n");
		}
		if($map->get_hint("rrd_default_out_ds") != '') {
			$dsnames[OUT] = $map->get_hint("rrd_default_out_ds");
			debug("Default 'out' DS name changed to ".$dsnames[OUT].".\n");
		}

		$multiplier = 8; // default bytes-to-bits

		$inbw = NULL;
		$outbw = NULL;
		$data_time = 0;

		if(preg_match("/^(.*\.rrd):([\-a-zA-Z0-9_]+):([\-a-zA-Z0-9_]+)$/",$targetstring,$matches)) {
			$rrdfile = $matches[1];
			$dsnames[IN] = $matches[2];
			$dsnames[OUT] = $matches[3];
			debug("Special DS names seen (".$dsnames[IN]." and ".$dsnames[OUT].").\n");
		}

		if(preg_match("/^rrd:(.*)/",$rrdfile,$matches))
		{
			$rrdfile = $matches[1];
		}

		if(preg_match("/^gauge:(.*)/",$rrdfile,$matches))
		{
			$rrdfile = $matches[1];
			$multiplier = 1;
		}

		if(preg_match("/^scale:([+-]?\d*\.?\d*):(.*)/",$rrdfile,$matches)) 
		{
				$rrdfile = $matches[2];
				$multiplier = $matches[1];
		}

		debug("SCALING result by $multiplier\n");
		
		// try and make a complete path, if we've been given a clue
		// (if the path starts with a . or a / then assume the user knows what they are doing)
		if(!preg_match("/^(\/|\.)/",$rrdfile))
		{
			$rrdbase = $map->get_hint('rrd_default_path');
			if($rrdbase != '')
			{
				$rrdfile = $rrdbase."/".$rrdfile;
			}
		}

		$cfname = intval($map->get_hint('rrd_cf'));
		if($cfname=='') $cfname='AVERAGE';
		
		$period = intval($map->get_hint('rrd_period'));
		if($period == 0) $period = 800;
		$start = $map->get_hint('rrd_start');
		if($start == '') {
		    $start = "now-$period";
		    $end = "now";
		}
		else
		{
		    $end = "start+".$period;
		}
		$start = time()-60;
		$end = time();
		if( ($dsnames[IN]!='-' && $data[IN] === NULL) || ($dsnames[OUT] !='-' && $data[OUT] === NULL) )	{
			if(file_exists($rrdfile)){
				error_log("RRD ReadData: Target DS names are ".$dsnames[IN]." and ".$dsnames[OUT]."\n");		
				$values=array();	
				WeatherMapDataSource_rrd::wmrrd_read_from_php_rrd($rrdfile,$cfname,$start,$end, $dsnames, $data,$map, $data_time,$item);
			}
			else
			{
				warn ("Target $rrdfile doesn't exist. Is it a file? [WMRRD06]\n");
			}
		}

		// if the Locale says that , is the decimal point, then rrdtool
		// will honour it. However, floatval() doesn't, so let's replace
		// any , with . (there are never thousands separators, luckily)
		//
		if($data[IN] !== NULL) {
			$data[IN] = floatval(str_replace(",",".",$data[IN]));
			$data[IN] = $data[IN] * $multiplier;
		}
		if($data[OUT] !== NULL) {
			$data[OUT] = floatval(str_replace(",",".",$data[OUT]));
			$data[OUT] = $data[OUT] * $multiplier;
		}
		debug ("RRD ReadData: Returning (".($data[IN]===NULL?'NULL':$data[IN]).",".($data[OUT]===NULL?'NULL':$data[OUT]).",$data_time)\n");
		return( array($data[IN], $data[OUT], $data_time) );
	}
}

// vim:ts=4:sw=4:
?>
